package com.stone.bigdata.config.ds;

import com.alibaba.druid.pool.DruidDataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;

@PropertySource("classpath:application.yml")
@Configuration
//@ConfigurationProperties(prefix = "spring.datasource.fota")
// 扫描 Mapper 接口并容器管理
@MapperScan(basePackages = FotaDataSourceConfig.PACKAGE, sqlSessionFactoryRef = "fotaSqlSessionFactory")
public class FotaDataSourceConfig {

    static final String PACKAGE = "com.stone.bigdata.dao.fota";
    static final String MAPPER_LOCATION = "classpath:mapper/fota/*.xml";

    @Value("${spring.datasource.fota.url}")
    private String url;

    @Value("${spring.datasource.fota.username}")
    private String user;

    @Value("${spring.datasource.fota.password}")
    private String password;

    @Value("${spring.datasource.fota.driverClassName}")
    private String driverClass;

    @Bean(name = "fotaDataSource")
    public DataSource fotaDataSource() {
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setDriverClassName(driverClass);
        dataSource.setUrl(url);
        dataSource.setUsername(user);
        dataSource.setPassword(password);
        return dataSource;
    }

    @Bean(name = "fotaTransactionManager")
    @Primary
    public DataSourceTransactionManager fotaTransactionManager() {
        return new DataSourceTransactionManager(fotaDataSource());
    }

    @Bean(name = "fotaSqlSessionFactory")
    @Primary
    public SqlSessionFactory fotaSqlSessionFactory(@Qualifier("fotaDataSource") DataSource fotaDataSource)
            throws Exception {
        final SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
        sessionFactory.setDataSource(fotaDataSource);
        sessionFactory.setMapperLocations(new PathMatchingResourcePatternResolver()
                .getResources(FotaDataSourceConfig.MAPPER_LOCATION));
        return sessionFactory.getObject();
    }
}